<template>
  <div>
    <a-spin :spinning="spinning" tip="Loading...">
      <a-form-model
        ref="form"
        :model="form.val"
        :rules="form.rules"
        :label-col="form.labelCol"
        :wrapper-col="form.wrapperCol"
      >
        <a-form-item label="资源" prop="menuIds">
          <a-tree
            :key="treeKey"
            :tree-data="menuTreeData"
            v-model="form.val.menuIds"
            :default-checked-keys="form.val.menuIds"
            :replace-fields="{ title: 'name', key: 'id' }"
            checkable
            show-line
            checkStrictly
            defaultExpandAll
            @check="onCheckMenus"
          />
        </a-form-item>
      </a-form-model>
    </a-spin>
    <a-form-item class="form-btn">
      <a-button @click="closeDetail(false)">取消</a-button>
      <a-button type="primary" :loading="form.confirmLoading" @click="onSubmit('form')">确定</a-button>
    </a-form-item>
  </div>
</template>

<script>
import { getRoleMenus, getMenuList, updateRoleMenus } from '@/api/system'
import { listToTree } from '@/utils/common'

export default {
  props: {
    currentInfo: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      spinning: false,
      menuTreeData: [],
      hiddenMenus: [],
      treeKey: 0,
      form: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 3 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 21 }
        },
        confirmLoading: false,
        val: {
          menuIds: []
        },
        rules: {
          name: [{ required: true, message: '名称不可为空', trigger: 'blur' }]
        }
      }
    }
  },
  watch: {
    'currentInfo.id': 'resetForm'
  },
  created () {
    this.getMenuData()
  },
  methods: {
    // 重构表单内容
    resetForm (val) {
      this.form.confirmLoading = false
      this.$nextTick(() => { // 清除表单验证结果
        this.$refs.form.clearValidate()
      })
      if (this.menuTreeData.length === 0) {
        this.$notification['warning']({
          message: '系统内暂无资源！',
          duration: 2
        })
        return
      }
      this.getInfo(val)
    },
    // 获取详情
    getInfo (id) {
      this.spinning = true
      getRoleMenus({ id }).then(res => {
        const data = res.content || []
        const currIds = data.map(item => item.id)
        currIds.unshift(this.setDefaultMenus())
        this.form.val.menuIds = currIds
        this.treeKey++
      }).finally(res => {
        this.spinning = false
      })
    },
    // 设置默认菜单
    setDefaultMenus () {
      const data = this.menuTreeData
      if (!data || !data.length) {
        return
      }
      return data[0].id
    },
    // 获取菜单数据
    getMenuData () {
      this.spinning = true
      getMenuList().then(res => {
        const list = res.content || []
        const menuNav = []
        listToTree(list, menuNav, 0)
        menuNav[0].disabled = true
        this.menuTreeData = menuNav
        this.treeKey++
      }).finally(() => {
        this.getInfo(this.currentInfo.id)
      })
    },
    // 获取选择菜单
    onCheckMenus (val, info) {
      this.form.val.menuIds = val.checked
    },
    // 关闭弹出框
    closeDetail (val) {
      this.form.confirmLoading = false
      this.$emit('emitToParent', val)
    },
    // 提交表单信息
    onSubmit (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.form.confirmLoading = true
          const { menuIds } = this.form.val
          const params = {
            resourcesIds: menuIds && menuIds.join(','),
            roleId: this.currentInfo.id
          }
          this.updateInfo(params)
        }
      })
    },
    // 修改表单信息接口相应
    updateInfo (params) {
      updateRoleMenus(params).then(response => {
        this.$message.success('修改成功！')
        this.closeDetail(true)
      }).finally(() => {
        this.form.confirmLoading = false
      })
    }
  }
}
</script>
